const { MerchantInfo } = require('../models');

// 验证淘宝链接格式并提取ID
function extractTaobaoId(shopUrl) {
  const regex = /^https:\/\/shop(\d{9})\.taobao\.com\/?$/;
  const match = shopUrl.match(regex);
  if (!match) {
    throw new Error('无效的淘宝店铺链接格式');
  }
  return match[1];
}

// 商家微信登录
exports.merchantWechatLogin = async (req, res) => {
  try {
    const { code, taobaoId } = req.body;
    
    // 检查商家是否已存在
    const existingMerchant = await MerchantInfo.findOne({
      where: { taobao_id: taobaoId }
    });

    if (existingMerchant) {
      // 商家已存在，返回商家信息
      return res.json({
        success: true,
        data: {
          merchantName: existingMerchant.merchant_name,
          taobaoId: existingMerchant.taobao_id
        }
      });
    }

    // 商家不存在，返回需要注册的标识
    return res.json({
      success: true,
      needRegister: true
    });

  } catch (error) {
    console.error('商家微信登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试'
    });
  }
};

// 商家注册
exports.merchantRegister = async (req, res) => {
  try {
    const { shopUrl, merchantName } = req.body;

    // 验证并提取淘宝ID
    let taobaoId;
    try {
      taobaoId = extractTaobaoId(shopUrl);
    } catch (error) {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }

    // 检查淘宝ID是否已被注册
    const existingMerchant = await MerchantInfo.findOne({
      where: { taobao_id: taobaoId }
    });

    if (existingMerchant) {
      return res.status(400).json({
        success: false,
        message: '该店铺已被注册'
      });
    }

    // 创建新商家
    const newMerchant = await MerchantInfo.create({
      merchant_name: merchantName,
      taobao_id: taobaoId
    });

    res.json({
      success: true,
      data: {
        merchantName: newMerchant.merchant_name,
        taobaoId: newMerchant.taobao_id
      }
    });

  } catch (error) {
    console.error('商家注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试'
    });
  }
}; 